package com.zyq.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyq.common.entity.course.subject.EduSubject;
import com.zyq.common.vo.Result;
import com.zyq.core.dao.SubjectDao;
import com.zyq.core.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 翟彦淇
 * @description TODO
 * @date 2022/12/5 20:49
 */
@Service
public class SubjectServiceImpl implements SubjectService {
    @Autowired
    private SubjectDao subjectDao;
    @Override
    public Result<List<EduSubject>> findSubjectByStatus() {
        // 1. 先将所有的科目查询出来  （筛选条件status_id为1  有效  被查询出来）
        QueryWrapper<EduSubject> eduSubjectQueryWrapper = new QueryWrapper<>();
        eduSubjectQueryWrapper.eq("status_id","1");
        List<EduSubject> eduSubjects = subjectDao.selectList(eduSubjectQueryWrapper);
        System.out.println("eduSubjects = " + eduSubjects);
        if(eduSubjects == null){
            return new Result<>(5000,"查询全部科目失败",null);
        }
        // 2. 通过parent_id把父科目提取出来，放到list里面
        List<EduSubject> first = new ArrayList<>();
        for (EduSubject eduSubject : eduSubjects) {
            if(eduSubject.getParentId().equals("0")){
                first.add(eduSubject);
            }
        }
        // 3. 利用方法递归，来完成子科目添加到父科目的下面
        for (EduSubject eduSubject : first) {
            eduSubject.setChildren(findChildren(eduSubjects,eduSubject.getId()));
        }

        System.out.println("first = " + first);
        return new Result<>(2000,"科目查询成功",first);
    }
    // 查找父科目下面的子科目，以及子科目下面的子科目  以及。。。。
    private List<EduSubject> findChildren(List<EduSubject> eduSubjects, String id){
        List<EduSubject> second = new ArrayList<>();
        // 整理出来二级科目
        for (EduSubject eduSubject : eduSubjects) {
            if(eduSubject.getParentId().equals(id)){
                second.add(eduSubject);
            }
        }
        // 递归调用
        for (EduSubject eduSubject : second) {
            eduSubject.setChildren(findChildren(eduSubjects,eduSubject.getId()));
        }

        return second;

    }
}
